<!-- 车辆预约-表单信息 part1 -->
<template>
	<view class="container">
		<view class="example">
			<uni-forms ref="baseForm" label-align="left" :modelValue="formData">
				<uni-forms-item label="车牌号" required name="code" labelWidth="auto" label-align="right">
					<view class="platecode" placeholder="请点此输入车牌号" @tap="plateShow = (!disabled && !isEditOption)">
						{{formData.code||"请点此输入车牌号"}}
					</view>
					<plate-input v-if="plateShow" :plate="formData.code" @export="setPlate"
						@close="plateShow = false" />
				</uni-forms-item>
				<uni-forms-item label="车辆类型" required name="type" labelWidth="auto" label-align="right">
					<view class="cartype">
						<uni-data-checkbox v-model="formData.type" :localdata="carType"></uni-data-checkbox>
					</view>
				</uni-forms-item>
				<uni-forms-item label="车牌颜色" required name="color" labelWidth="auto">
					<picker @change="colorChange" :value="colorIndex" :range="colorLists" :disabled="disabled">
						<view class="uni-input color">{{colorLists[colorIndex]}}</view>
					</picker>
				</uni-forms-item>
				<!-- <block v-if="qfIsShow">
					<uni-forms-item label="挂车号" required name="trailercode" labelWidth="auto" label-align="right">
						<input class="platecode" placeholder="请点此输入" disabled="inputDisabled"
							@tap="TrailerPlateShow = (!disabled|| isEdit)" v-model.trim="formData.trailercode"
							:disabled="disabled" />
						<plate-input v-if="TrailerPlateShow" :plate="formData.trailercode" @export="setTrailerCode"
							@close="TrailerPlateShow = false" />
					</uni-forms-item>
				</block> -->
				<uni-forms-item label="营运公司" name="enterprise" labelWidth="auto" label-align="right">
					<uni-easyinput v-model="formData.enterprise" placeholder="请输入营运公司" :disabled="disabled" />
				</uni-forms-item>
				<uni-forms-item label="车架号" name="drivingpermit" labelWidth="auto" label-align="right" v-if="isShowVin">
					<!-- <uni-easyinput v-model="formData.drivingpermit" @input="vinInput"  :value="formData.drivingpermit" maxlength="17" placeholder="请输入"
						:disabled="disabled && !isEdit" /> -->
					<view class="vinbox">
						<input type="text" placeholder="请输入17位VIN码" maxlength="17" @input="vinInput"
							:value="formData.drivingpermit" :disabled="disabled && !isEdit" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="填报人电话" required name="linkphone" labelWidth="auto" label-align="right">
					<uni-easyinput v-model="formData.linkphone" placeholder="请输入填报人电话" type="number"
						:disabled="disabled && !isEdit" />
				</uni-forms-item>
				<view class="col-gap"></view>
				<uni-forms-item label="行驶证照片" :required="(formData.type=='0'||formData.type=='4')?true:false"
					name="drivingpermitimage" labelWidth="auto" label-align="right">
					<view class="add-img-box">
						<view class="add-img-item" v-for="(item, index) in permitImgList" :key="index">
							<image class="add-img" @click="imgInfo(1,index)" :src="item.path" mode="aspectFill">
							</image>
							<image v-if="!disabled" class="add-img-del" @click="delImg(1,index)"
								src="../../static/img/icon/icon_del.png"></image>
						</view>
						<view v-if="permitImgList.length < permitImgCount && !disabled" class="add-img-item"
							@click="openCamera(1)">
							<image class="add-img" src="../../static/img/add.png"></image>
						</view>
					</view>
				</uni-forms-item>
				<uni-forms-item label="车辆照片" :required="(formData.type=='0'||formData.type=='4')?true:false"
					name="carimage" labelWidth="auto" label-align="right">
					<view class="add-img-box" style="padding-left: 15px;">
						<view class="add-img-item" v-for="(item, index) in carImgList" :key="index">
							<image class="add-img" @click="imgInfo(2,index)" :src="item.path" mode="aspectFill">
							</image>
							<image v-if="!disabled" class="add-img-del" @click="delImg(2,index)"
								src="@/static/img/icon/icon_del.png"></image>
						</view>
						<view v-if="carImgList.length < imgCount && !disabled" class="add-img-item"
							@click="openCamera(2)">
							<image class="add-img" src="@/static/img/add.png"></image>
						</view>
					</view>
				</uni-forms-item>
				<block v-if="qfIsShow">
					<uni-forms-item label="资质照片" :required="(formData.type=='0'||formData.type=='4')?true:false"
						name="qualification" labelWidth="auto" label-align="right">
						<view class="add-img-box" style="padding-left: 15px;">
							<view class="add-img-item" v-for="(item, index) in qualificationList" :key="index">
								<image class="add-img" @click="imgInfo(3,index)" :src="item.path" mode="aspectFill">
								</image>
								<image v-if="!disabled" class="add-img-del" @click="delImg(3,index)"
									src="@/static/img/icon/icon_del.png"></image>
							</view>
							<view v-if="qualificationList.length < qualificationCount && !disabled" class="add-img-item"
								@click="openCamera(3)">
								<image class="add-img" src="@/static/img/add.png"></image>
							</view>
						</view>
					</uni-forms-item>
				</block>
			</uni-forms>
		</view>
		<view class="btn-box" v-if="!disabled|| isEdit">
			<button class="btn1" type="warn" size="mini" @click="doSubmit('baseForm')"> 确定 </button>
			<button class="btn2 ml10" type="warn" size="mini" plain="true" @click="doCancel()"> 取消 </button>
		</view>
		<!-- 提示信息弹窗 -->
		<uni-popup ref="message" type="message">
			<uni-popup-message :type="msgType" :message="messageText" :duration="5000"></uni-popup-message>
		</uni-popup>
	</view>
</template>

<script>
	import {
		Platform,
		Storage_Key,
		ProjectStates,
		ProjectKeys,
		PlateColor,
		CarSetting,
		UserJobsType
	} from '@/static/config.js';
	import {
		GetCardColor,
	} from '@/common/util.js';
	import {
		IsCorrectVin
	} from '@/common/vin.js';
	import request from '@/common/request.js';
	import plateInput from '@/components/uni-plate-input/uni-plate-input.vue';
	export default {
		components: {
			plateInput
		},
		computed: {
			wxUserInfo() {
				return this.$storage.get(Storage_Key.user_info, true);
			},
			webUserInfo() {
				return this.$storage.get(Storage_Key.web_user_info, true);
			},
		},
		data() {
			return {
				carType: CarSetting.cartypeUseByAdd,
				adminLists: [], // 园区管理员数据
				//车牌号相关属性
				plateShow: false,
				//挂车车牌号相关属性
				// TrailerPlateShow: false,
				inputDisabled: true,
				// 提示信息弹窗
				type: 'center',
				msgType: 'success',
				messageText: '这是一条成功提示',

				//图片上传
				permitImgList: [], // 行驶证上传图片信息
				carImgList: [], // 车辆上传图片信息
				qualificationList: [], // 资质图片
				permitImgCount: 3,
				imgCount: 3,
				qualificationCount: 6,
				disabled: false, // 是否只读
				isEdit: true, // 是否可改
				isEditOption: false, // 是否点击修改按钮
				qfIsShow: true, // 车辆资质显隐
				//表单信息
				formData: {
					id: "",
					code: "", // 车牌号
					color: PlateColor[1], //车辆颜色 默认
					enterprise: "", //所属企业
					drivingpermit: "", //车架号
					carimage: "", // 车辆图片ID，逗号隔开
					drivingpermitimage: "", // 行驶证图片ID，逗号隔开
					carimagepath: "", // 车辆图片完整path，逗号隔开
					drivingpermitimagepath: "", // 行驶证图片完整path，逗号隔开
					qualification: "", // 资质图片ID，逗号隔开
					qualificationimagepath: "", // 资质图片完整path，逗号隔开
					creatorid: "",
					creator: "",
					createtime: 0,
					updaterid: "",
					updater: "",
					updatetime: 0,
					// trailercode: "", //挂车车牌号
					linkphone: "", //填报人电话
					type: '0'
				},
				carData: [], // 查询的车辆数据
				colorLists: PlateColor, //车牌颜色
				colorIndex: 1,
				olddrivingpermit: "", //修改前车架号
				tkibtn: false, //是否从tkitree组件点击+号按钮
				isShowVin: true, //是否显示车架号
				// 校验规则
				formRules: {
					type: {
						rules: [{
							required: true,
							errorMessage: '请选择车辆类型'
						}]
					},
					code: {
						rules: [{
							required: true,
							errorMessage: '车牌号不能为空'
						}]
					},
					// drivingpermit: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '请输入车架号'
					// 	}]
					// },
					linkphone: {
						rules: [{
							required: true,
							errorMessage: '填报人电话不能为空'
						}, {
							validateFunction: function(rule, value, data, callback) {
								let reg =
									/^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$/;
								if (!reg.test(value)) {
									return callback('手机号格式不正确')
								}
							}
						}]
					},
				},
			}
		},
		onReady() {
			this.$refs.baseForm.setRules(this.formRules)
		},
		onBackPress() {
			console.log('返回了')
			let arr = ""
			if (this.formData.drivingpermitimages != "") {
				arr += this.formData.drivingpermitimage
			}
			if (this.formData.carimage != "") {
				arr += "," + this.formData.carimage
			}
			if (this.formData.qualification != "") {
				arr += "," + this.formData.qualification
			}
			if (arr != '') {
				let array = arr.split(',')
				console.log(array)
				array.forEach(ite => {
					uni.request({
						url: Platform.api_requestUrl + '/stp-common-file/deletefile',
						data: {
							fileid: ite,
						},
						header: {},
						method: 'GET',
						success: (res) => {
							console.log(res)
						}
					})
				})
			}

		},
		onLoad(options) {
			let _self = this;
			if (options.tkibtn) {
				_self.tkibtn = true;
			}
			if (options && options.item) {
				_self.permitImgList = [],
					_self.carImgList = [];
				_self.qualificationList = [];
				_self.formData = JSON.parse(decodeURIComponent(options.item));
				_self.colorIndex = _self.getCardColor(_self.formData.color).index;

				if (options.isEditOption) {
					_self.isEditOption = true;
					_self.isShowVin = true; //编辑车辆时显示车架号 
					_self.olddrivingpermit = _self.formData.drivingpermit;
					_self.formData.drivingpermit = ""; //不显示车架号值
				}
				if (options.disabled) {
					_self.disabled = options.disabled;
					_self.isEdit = false; // 查看 - 不可改
				}
				_self.initImge();

			}
			_self.getcartype();
			_self.initData();

		},
		methods: {
			aa() {
				alert(123)
			},
			// 初始化数据
			initData() {
				let _self = this;
				// _self.formData.creatorid = _self.wxUserInfo.openId || "";
				// _self.formData.creator = _self.wxUserInfo.nickName || "";
				// _self.formData.updaterid = _self.wxUserInfo.openId || "";
				// _self.formData.updater = _self.wxUserInfo.nickName || "";
				_self.formData.openid = _self.wxUserInfo.openId || "";
				// _self.formData.userid = !!_self.webUserInfo ? _self.webUserInfo.user.userId : "";
				if (!_self.disabled) {
					// 获取园区管理员数据
					this.loadDestinationData();
				}

			},
			getcartype() {
				uni.request({
					url: Platform.api_requestUrl + '/stp-car/getCartypes',
					method: 'GET',
					success: (res) => {
						console.log(res)
					},
				})
			},
			// 照片处理
			initImge() {
				let _self = this;
				_self.permitImgList = [];
				_self.carImgList = [];
				_self.qualificationList = [];
				// 行驶证照片
				if ((!!_self.formData.drivingpermitimage) && (!!_self.formData.drivingpermitimagepath)) {
					let permitImgListTemp = _self.formData.drivingpermitimage.split(','); // 与path一一对应
					let permitImgListPathTemp = _self.formData.drivingpermitimagepath.split(',');
					permitImgListPathTemp.forEach((item, index) => {
						_self.permitImgList.push({
							"id": permitImgListTemp[index],
							"path": item
						});
					})
				}
				// 车辆照片
				if ((!!_self.formData.carimage) && (!!_self.formData.carimagepath)) {
					let carImgListTemp = _self.formData.carimage.split(','); // 与path一一对应
					let carImgListPathTemp = _self.formData.carimagepath.split(',');
					carImgListPathTemp.forEach((item, index) => {
						_self.carImgList.push({
							"id": carImgListTemp[index],
							"path": item
						});
					})
				}
				// 资质照片
				if ((!!_self.formData.qualification) && (!!_self.formData.qualificationimagepath)) {
					_self.qfIsShow = true;
					let qualificationListTemp = _self.formData.qualification.split(','); // 与path一一对应
					let qualificationListPathTemp = _self.formData.qualificationimagepath.split(',');
					qualificationListPathTemp.forEach((item, index) => {
						_self.qualificationList.push({
							"id": qualificationListTemp[index],
							"path": item
						});
					})
				} else {
					_self.qfIsShow = false;
				}
			},
			getCardColor(val) {
				return GetCardColor(val);
			},
			setPlate(plate) {
				if (plate.length >= 7) {
					//检索车牌信息数据库中是否已经存在
					this.loadCarData(plate);
					this.formData.code = plate;
					this.plateShow = false;
					// 车牌号改变 - 各组件可用状态
					this.disabled = false;
				}
			},
			//设置挂车车牌号
			// setTrailerCode(plate) {
			// 	if (plate.length >= 7) {
			// 		//检索车牌信息数据库中是否已经存在
			// 		this.loadCarData(plate);
			// 		this.formData.trailercode = plate;
			// 		this.TrailerPlateShow = false;
			// 		// 车牌号改变 - 各组件可用状态
			// 		this.disabled = false;
			// 	}
			// },
			// 获取园区管理员数据
			loadDestinationData() {
				let _self = this;
				request({
					url: Platform.api_requestUrl + '/osp-basemain-organization/GetOrganizationDataAdmin',
					data: {
						code: Platform.code,
						roleName: UserJobsType[4].text // 园区管理员
					},
					method: 'GET',
				}).then(response => {
					uni.hideLoading();
					if (response.code == 200) {
						_self.adminLists = response.data.peoples;
					} else {
						_self.messageToggle('error', response.message || '查询失败');
					}
				}).catch(error => {
					uni.hideLoading();
					uni.showModal({
						content: '查询失败',
						showCancel: false
					})
				});
			},
			loadCarData(plate) {
				let _self = this;
				let totalcount = -1;
				request({
					url: Platform.api_requestUrl + '/stp-car/getListDetail',
					method: 'GET',
					data: {
						pageIndex: 1,
						pageSize: 100000000,
						carCode: plate,
						creatorid: "",
						updaterid: ""
					},
				}).then(res => {
					if (res.code == 200 && !!res.data.length != 0) {
						_self.$refs.baseForm.setRules(_self.formRules)
						let _list = res.data;
						let item = _list[0];
						_self.formData = Object.assign({}, item);
						_self.carData = _list[0]; //原来车辆数据
						// 已有车辆信息 - 各组件禁用状态
						_self.disabled = true;
						_self.isShowVin = false; //已有车辆信息车辆时不显示车架号
						// 赋值当前用户微信账号ID
						// _self.formData.updaterid = _self.wxUserInfo.openId || "";
						// _self.formData.updater = _self.wxUserInfo.nickName || "";
						// _self.formData.openid = _self.wxUserInfo.openId || ""; // 赋值当前用户微信账号ID

						//20221125修改，绑定车辆时不验证车架号
						// _self.formData.drivingpermit = ""; //车架号置成空
						//处理图片路径 回显使用
						_self.initImge();
					} else {
						_self.carData = []; // 查询的车辆数据
						// 已有车辆信息 - 各组件禁用状态
						_self.disabled = false;
						// 没有查询到已有车辆信息，将UI数据置空，除了code车牌号
						_self.formData.id = "";
						_self.formData.drivingpermitimage = ""; // 行驶证照片
						_self.formData.carimage = ""; // 车辆照片
						_self.formData.qualification = ""; // 资质照片
						carimagepath: ""; // 车辆图片完整path，逗号隔开
						drivingpermitimagepath: ""; // 行驶证图片完整path，逗号隔开
						qualification: ""; // 资质图片ID，逗号隔开
						qualificationimagepath: ""; // 资质图片完整path，逗号隔开
						_self.permitImgList = [];
						_self.carImgList = [];
						_self.qualificationList = [];
						_self.formData.color = PlateColor[1]; // 车牌颜色
						_self.formData.colorIndex = 1;
						_self.formData.enterprise = ""; // 所属企业
						_self.formData.drivingpermit = ""; //车架号码

					}

				}).catch(error => {
					console.log("fail", error)
				});

				// uni.request({
				// 	url: Platform.api_requestUrl + '/stp-car/getListDetail',
				// 	data: {
				// 		pageIndex: 1,
				// 		pageSize: 100000000,
				// 		carCode: plate,
				// 		creatorid: "",
				// 		updaterid: ""
				// 	},
				// 	header: {},
				// 	method: 'GET',
				// 	success: (res) => {
				// 		if (res.data.code == 200 && !!res.data.data.length != 0) {
				// 			_self.$refs.baseForm.setRules(_self.formRules)
				// 			let _list = res.data.data;
				// 			let item = _list[0];
				// 			_self.formData = Object.assign({}, item);
				// 			_self.carData = _list[0]; //原来车辆数据
				// 			// 已有车辆信息 - 各组件禁用状态
				// 			_self.disabled = true;
				// 			_self.isShowVin = false; //已有车辆信息车辆时不显示车架号
				// 			// 赋值当前用户微信账号ID
				// 			// _self.formData.updaterid = _self.wxUserInfo.openId || "";
				// 			// _self.formData.updater = _self.wxUserInfo.nickName || "";
				// 			// _self.formData.openid = _self.wxUserInfo.openId || ""; // 赋值当前用户微信账号ID
				// 			//20221125修改，绑定车辆时不验证车架号
				// 			// _self.formData.drivingpermit = ""; //车架号置成空
				// 			//处理图片路径 回显使用
				// 			_self.initImge();
				// 		} else {
				// 			_self.carData = []; // 查询的车辆数据
				// 			// 已有车辆信息 - 各组件禁用状态
				// 			_self.disabled = false;
				// 			// 没有查询到已有车辆信息，将UI数据置空，除了code车牌号
				// 			_self.formData.id = "";
				// 			_self.formData.drivingpermitimage = ""; // 行驶证照片
				// 			_self.formData.carimage = ""; // 车辆照片
				// 			_self.formData.qualification = ""; // 资质照片
				// 			carimagepath: ""; // 车辆图片完整path，逗号隔开
				// 			drivingpermitimagepath: ""; // 行驶证图片完整path，逗号隔开
				// 			qualification: ""; // 资质图片ID，逗号隔开
				// 			qualificationimagepath: ""; // 资质图片完整path，逗号隔开
				// 			_self.permitImgList = [];
				// 			_self.carImgList = [];
				// 			_self.qualificationList = [];
				// 			_self.formData.color = PlateColor[1]; // 车牌颜色
				// 			_self.formData.colorIndex = 1;
				// 			_self.formData.enterprise = ""; // 所属企业
				// 			_self.formData.drivingpermit = ""; //车架号码
				// 		}
				// 	},
				// 	complete: () => {
				// 		console.log("complete")
				// 	},
				// 	fail: (error) => {
				// 		console.log("fail")
				// 	},
				// });
			},
			messageToggle(type, msg) {
				this.msgType = type
				this.messageText = msg
				this.$refs.message.open()
			},
			// recruitStart(e) {
			// 	this.formData.intime = e.dt.getTime();
			// },
			// recruitEnd(e) {
			// 	let rs = new Date(this.formData.intime).getTime();
			// 	let re = e.dt.getTime();
			// 	if (rs > re) {
			// 		this.formData.outtime = ''
			// 		this.$refs.datePickerRecEnd.dateStr = '>' //-----
			// 		this.formData.intime = ''
			// 		this.$refs.datePickerProStart.dateStr = '>' //-----
			// 		this.formData.outtime = ''
			// 		this.$refs.datePickerProEnd.dateStr = '>' //-----
			// 		this.messageToggle('error', '计划驶出时间应该在计划驶入时间之后！')
			// 		return
			// 	}
			// 	this.formData.outtime = re;
			// },
			colorChange(e) {
				this.formData.color = PlateColor[e.target.value]
				this.colorIndex = e.target.value
				// 控制车辆资质图片模块
				if (CarSetting.controlQfTpyes.includes(this.formData.color)) {
					this.qfIsShow = true;
				} else {
					this.qfIsShow = false;
				}
			},
			openCamera(val) {
				let _self = this;

				// 最多可以选择的图片张数
				let count = 1;
				if (val == 1) {
					count = this.permitImgCount;
				} else if (val == 2) {
					count = this.imgCount;
				} else {
					count = this.qualificationCount;
				}

				// **************** 从本地相册选择图片或使用相机拍照 ****************
				uni.chooseImage({
					sourceType: ['album', 'camera'], //album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
					count: count, // 最多可以选择的图片张数，默认9
					sizeType: ['original', 'compressed'], //['original', 'compressed'] 可以指定是原图还是压缩图，默认二者都有
					success: e => { //成功则返回图片的本地文件路径列表 tempFilePaths
						// tempFilePaths 图片的本地文件路径列表；tempFiles 图片的本地文件列表，每一项是一个 File 对象（path、size、name）
						// 控制剩余可选数
						if (val == 1) {
							_self.permitImgList = [..._self.permitImgList, ...e.tempFiles];
							_self.commitFiles();
						} else if (val == 2) {
							_self.carImgList = [..._self.carImgList, ...e.tempFiles];
							_self.commitCarFiles();
						} else {
							_self.qualificationList = [..._self.qualificationList, ...e.tempFiles];
							_self.commitQualificationFiles();
						}
					}
				});
			},
			imgInfo(v, i) {
				let tempList = [];
				if (v == 1) {
					// tempList = [];
					this.permitImgList.forEach(img => {
						tempList.push(img.path);
					});
				}
				if (v == 2) {
					// tempList = [];
					this.carImgList.forEach(img => {
						tempList.push(img.path);
					});
				}
				if (v == 3) {
					// tempList = [];
					this.qualificationList.forEach(img => {
						tempList.push(img.path);
					});
				}
				// **************** 预览图片 ****************
				uni.previewImage({
					current: i, //为当前显示图片的链接/索引值，不填或填写的值无效则为 urls 的第一张
					loop: false, //是否可循环预览，默认值为 false
					urls: tempList, //需要预览的图片链接列表
					indicator: 'default' //图片指示器样式，可取值："default" - 底部圆点指示器； "number" - 顶部数字指示器； "none" - 不显示指示器。
					// longPressActions:长按图片显示操作菜单，如不填默认为保存相册
					// success
					// fail
					// complete
				});
			},
			delImg(v, i) {
				uni.showModal({
					content: '确定删除这张吗',
					success: res => {
						if (res.confirm) {
							if (v == 1) {
								request({
									url: Platform.api_requestUrl + '/stp-common-file/deletefile',
									data: {
										fileid: this.permitImgList[i].upid,
									},
									method: 'GET',
								}).then(res => {
									console.info(res);
								}).catch(error => {
									console.error(error);
								});
								this.permitImgList.splice(i, 1);
								this.permitImgCount++;

							}
							if (v == 2) {
								request({
									url: Platform.api_requestUrl + '/stp-common-file/deletefile',
									data: {
										fileid: this.carImgList[i].upid,
									},
									method: 'GET',
								}).then(res => {
									console.info(res);
								}).catch(error => {
									console.error(error);
								});
								this.carImgList.splice(i, 1);
								this.imgCount++;
							}
							if (v == 3) {
								request({
									url: Platform.api_requestUrl + '/stp-common-file/deletefile',
									data: {
										fileid: this.qualificationList[i].upid,
									},
									method: 'GET',
								}).then(res => {
									console.info(res);
								}).catch(error => {
									console.error(error);
								});
								this.qualificationList.splice(i, 1);
								this.qualificationImgCount++;
							}
						} else if (res.cancel) {}
					}
				});
			},
			vinInput(e) {
				let val = e.detail.value;
				if (/[^a-zA-Z0-9]/g.test(val)) { // 先过滤不需要的字符，只保留数字和字母
					val = val.replace(/[^a-zA-Z0-9]/g, '');
				}
				if (!/^[A-Z\d]+$/.test(val)) { // 再进行转换，小写转为大写
					val = val.toUpperCase();
				}
				this.formData.drivingpermit = val; //这里对应的是value绑定的变量
				//return val; // 最后输出值，要保证输入框的值和value绑定的值一致
			},
			doSubmit(ref) {
				let _self = this;
				//20221125修改 绑定车辆时不验证车架号是否一致，修改车辆信息时进行验证
				// if (_self.carData.length != 0 && !!_self.carData) {
				// 	//判断输入的车架号与已经存在的是否一致
				// 	if (_self.carData.drivingpermit == _self.formData.drivingpermit) {
				// 		//执行修改程序
				// 		_self.SaveOrUpdateCarInfo(ref);
				// 	} else {
				// 		_self.messageToggle('error', '输入的车架号与车辆绑定的车架号不一致，请确认后重新输入！');
				// 	}
				// } else {
				// 	_self.SaveOrUpdateCarInfo(ref);
				// }
				_self.SaveOrUpdateCarInfo(ref);
			},
			//保存车辆输入至数据库
			SaveOrUpdateCarInfo(ref) {
				let _self = this;
				console.log(_self.$refs[ref].validate())
				console.log(_self.formData)
				_self.$refs[ref].validate().then(async res => {

					// await _self.commitFiles(); //上传行驶证
					// await _self.commitCarFiles(); //上传车辆图片
					// await _self.commitQualificationFiles(); //上传资质图片

					// 校验VIN（车架号：LFV3A24FX93027358	 	LHGRY1852L2028418）
					// if (!_self.isCorrectVin(_self.formData.drivingpermit)) {
					// 	_self.messageToggle('error', '请输入正确的车架号！');
					// 	return;
					// }
					//修改操作 验证车架号
					// if (_self.isEditOption) {
					// 	if (_self.formData.drivingpermit.length < 17) {
					// 		_self.messageToggle('error', '请输入正确的车架号！');
					// 		return;
					// 	}
					// } else {
					// 	if (_self.formData.drivingpermit.length < 17 && _self.isShowVin) {
					// 		_self.messageToggle('error', '请输入正确的车架号！');
					// 		return;
					// 	}
					// }
					if (_self.formData.type == '0' || _self.formData.type == '4') {
						// 验证行驶证照片
						if (_self.formData.drivingpermitimage.length <= 0) {
							_self.messageToggle('error', '请上传行驶证照片！');
							return;
						}
						// 验证车辆照片
						if (_self.formData.carimage.length <= 0) {
							_self.messageToggle('error', '请上传车辆照片！');
							return;
						}
						// 验证资质照片
						if (CarSetting.controlQfTpyes.includes(_self.formData.color)) {
							if (_self.formData.qualification.length <= 0) {
								_self.messageToggle('error', '请上传资质照片！');
								return;
							}
						}
					}


					// 车辆绑定：非第一人时，不需要审核
					if (_self.carData.length == 0) { // 初次添加此车辆
						// 平台配置 - 是否需要审批
						request({
							url: Platform.api_requestUrl + '/stp-car/getapplication',
							data: {
								key: 'approve_car_add'
							},
							method: 'GET',
						}).then(response => {
							if (response.code == 200) {
								if (response.data === 'true') {
									_self.formData.state = '0'; // 审批状态 - 待审批
								} else {
									_self.formData.state = '1'; // 审批状态 - 默认通过
								}
							}
						}).catch(error => {
							console.error(error);
						});
						// if (Platform.auth.approve_car_add) {
						// 	// 0：未审核，1：已审核，2：未通过
						// 	_self.formData.state = '0'; // 审批状态 - 待审批
						// } else {
						// 	_self.formData.state = '1'; // 审批状态 - 默认通过
						// }
					} else {
						_self.formData.state = '1'; // 审批状态 - 默认通过
					}
					//修改操作
					if (_self.isEditOption) {
						_self.formData.updaterid = _self.wxUserInfo.openId;
						_self.formData.updater = _self.wxUserInfo.nickName;
						let tt = _self.olddrivingpermit;
						//202211月25日添加，修改车辆验证车架号是否与数据库中一致
						if (_self.olddrivingpermit == _self.formData.drivingpermit) {
							uni.showLoading({
								title: '提交中...',
								mask: true
							});
							//仅修改车辆信息
							_self.doModifyCarInfo()
						} else {
							_self.messageToggle('error', '输入的车架号与车辆绑定的车架号不一致，请确认后重新输入！');
						}

					} else {
						uni.showLoading({
							title: '提交中...',
							mask: true
						});
						//添加操作
						_self.formData.creatorid = _self.wxUserInfo.openId;
						_self.formData.creator = _self.wxUserInfo.nickName;
						_self.formData.openid = _self.wxUserInfo.openId || "";
						//车辆人员绑定
						_self.doSaveOrUpdateCarBindInfo();
					}
				}).catch(err => {
					console.log('err', err);
				})
			},
			//新增车辆逻辑
			doSaveOrUpdateCarBindInfo() {
				let _self = this;
				request({
					url: Platform.api_requestUrl + '/stp-car/SaveOrUpdateCarBindInfo',
					data: _self.formData,
					method: 'POST',
				}).then(response => {
					uni.hideLoading();
					if (response.code == 200) {
						// 返回的信息
						let res = response.data;
						// 车辆绑定：非第一人时，不需要审核
						if (_self.carData.length == 0) {
							// 平台配置 - 是否需要审批
							if (Platform.auth.approve_car_add) {
								// 添加审批流程
								let form = {
									creatorid: res.updaterid, // 提交人id
									creator: res.updater, // 提交人姓名
									updaterid: _self.adminLists.length > 0 ? _self
										.adminLists[
											0].id : '', // 审批人id
									updater: _self.adminLists.length > 0 ? _self
										.adminLists[0]
										.name : '', // 审批人姓名
									carid: res.id, // 车辆id
									// phone: _self.adminLists.length > 0 ? _self.adminLists[0].phone : '' // 审批人电话
								}
								_self.doSubmitApproval(form);
							}
						}
						if (_self.tkibtn) {
							//直接跳转到预约记录添加页面
							uni.redirectTo({
								url: '/pages/booking/booking-car-add?code=' + _self.formData.code +
									'&params=' + _self.formData.type
							})
						} else {
							uni.redirectTo({
								url: '/pages/car/my-car-list'
							})
						}
					} else {
						_self.messageToggle('error', response.message || '提交失败');
					}
				}).catch(error => {
					uni.hideLoading();
					uni.showModal({
						content: '保存失败',
						showCancel: false
					})
				});
			},

			doCancel() {
				uni.navigateBack();
			},
			// 添加审批流程
			doSubmitApproval(info) {
				request({
					url: Platform.api_requestUrl + '/stp-car-approval/SaveOrUpdate',
					data: info,
					method: 'POST',
				}).then(response => {
					uni.hideLoading();
					if (response.code == 200) {} else {}
				}).catch(error => {
					console.error(error);
				});
			},
			// 行驶证图片上传
			async commitFiles() {
				uni.showLoading({
					title: '上传中...',
					mask: true
				});
				let _self = this;
				let promise;
				let attachfileids = []; //附件上传后的id数组；
				// uni.showLoading({
				// 	title: '上传...',
				// 	mask: false
				// });
				// return new Promise((resolve, reject) => {
				// App支持多文件上传，微信小程序只支持单文件上传，传多个文件需要反复调用本API。所以跨端的写法就是循环调用本API。
				let permitImgListNew = _self.permitImgList.filter(e => !!e
					.size) // 新照片文件 --> 上传
				let permitImgListOld = _self.permitImgList.filter(e => !e
					.size) // 旧照片文件 --> 用ID（旧照片已经上传，无需再传，只需保存文件ID）
				console.log(permitImgListNew)
				console.log(_self.permitImgList)
				if (permitImgListNew.length > 0) {
					// for (let i = 0; i < permitImgListNew.length; i++) {
					// if (!permitImgListNew[permitImgListNew.length-1].size) break;
					uni.uploadFile({
						url: Platform.api_requestUrl + '/stp-common-file/upload',
						filePath: permitImgListNew[permitImgListNew.length - 1].path,
						name: 'file', //与服务器端匹配
						// formData: {
						// 	// 'files': permitImgListNew[i]
						// 	linkid: link
						// },
						// header: {
						// 	"Content-Type": "multipart/form-data"
						// },
						success: (uploadFileRes) => {
							let data = JSON.parse(uploadFileRes.data);
							uni.hideLoading();
							if (data.code == 200) {
								attachfileids.push(data.data.id); // 返回服务器图片
								_self.permitImgList[_self.permitImgList.length - 1].upid = data.data.id
								// 图片全部上传后
								// if (attachfileids.length == permitImgListNew
								// 	.length) {
								// 整合新照片和旧照片的ID
								// let ids = [...(permitImgListOld.map(e => e
								// 		.id)), ...
								// 	attachfileids
								// ]
								let ids = []
								if (_self.formData.drivingpermitimage.length > 0) {
									ids = [...[_self.formData.drivingpermitimage], ...
										attachfileids
									]
								} else {
									ids = [...attachfileids]
								}

								_self.formData.drivingpermitimage = ids
									.join(
										","); //附件编号					
								console.log(_self.formData.drivingpermitimage)
								// _self.formData.drivingpermitimage = attachfileids.join(
								// 	","); //附件编号
								resolve(attachfileids)
								// this.messageToggle('success', '提交成功');
								// uni.switchTab({
								// 	url: '/pages/user/user'
								// })
								// }
							} else {
								uni.showModal({
									content: '上传失败',
									showCancel: false
								})
							}
						},
						fail(e) {
							reject(e)
						}
					});
					// }
				} else {
					// 没有新照片时，需赋值最新的旧照片数据（可能进行了删除操作）
					let ids = [...(permitImgListOld.map(e => e.id))]
					_self.formData.drivingpermitimage = ids.join(","); //附件编号	
					resolve(true)
				}
				// })
			},
			// 车辆图片上传
			async commitCarFiles(link) {
				uni.showLoading({
					title: '上传中...',
					mask: true
				});
				let _self = this;
				let attachfileids = []; //附件上传后的id数组；

				// return new Promise((resolve, reject) => {
				// App支持多文件上传，微信小程序只支持单文件上传，传多个文件需要反复调用本API。所以跨端的写法就是循环调用本API。
				let carImgListNew = _self.carImgList.filter(e => !!e.size) // 新照片文件 --> 上传
				let carImgListOld = _self.carImgList.filter(e => !e
					.size) // 旧照片文件 --> 用ID（旧照片已经上传，无需再传，只需保存文件ID）
				if (carImgListNew.length > 0) {
					// 	for (let i = 0; i < carImgListNew.length; i++) {
					uni.uploadFile({
						url: Platform.api_requestUrl +
							'/stp-common-file/upload',
						filePath: carImgListNew[carImgListNew.length - 1].path,
						name: 'file', //与服务器端匹配
						success: (uploadFileRes) => {
							let data = JSON.parse(uploadFileRes.data);
							uni.hideLoading();
							if (data.code == 200) {
								attachfileids.push(data.data
									.id); // 返回服务器图片
								_self.carImgList[_self.carImgList.length - 1].upid = data.data.id
								// 图片全部上传后
								// if (attachfileids.length == carImgListNew
								// 	.length) {
								// 整合新照片和旧照片的ID
								// let ids = [...(carImgListOld.map(e => e
								// 		.id)), ...
								// 	attachfileids
								// ]
								let ids = []
								if (_self.formData.carimage.length > 0) {
									ids = [...[_self.formData.carimage], ...
										attachfileids
									]
								} else {
									ids = [...attachfileids]
								}
								_self.formData.carimage = ids.join(
									","); //附件编号		
								resolve(attachfileids);
								// }
							} else {
								uni.showModal({
									content: '上传失败',
									showCancel: false
								})
							}
						},
						fail(e) {
							reject(e)
						}
					});
					// }
				} else {
					// 没有新照片时，需赋值最新的旧照片数据（可能进行了删除操作）
					let ids = [...(carImgListOld.map(e => e.id))]
					_self.formData.carimage = ids.join(","); //附件编号		
					resolve(true)
				}
				// })
			},
			// 资质图片上传
			async commitQualificationFiles(link) {
				uni.showLoading({
					title: '上传中...',
					mask: true
				});
				let _self = this;
				let attachfileids = []; //附件上传后的id数组；

				// return new Promise((resolve, reject) => {
				// App支持多文件上传，微信小程序只支持单文件上传，传多个文件需要反复调用本API。所以跨端的写法就是循环调用本API。
				let qualificationListNew = _self.qualificationList.filter(e => !!e
					.size) // 新照片文件 --> 上传
				let qualificationListOld = _self.qualificationList.filter(e => !e
					.size) // 旧照片文件 --> 用ID（旧照片已经上传，无需再传，只需保存文件ID）
				if (qualificationListNew.length > 0) {
					// for (let i = 0; i < qualificationListNew.length; i++) {
					uni.uploadFile({
						url: Platform.api_requestUrl +
							'/stp-common-file/upload',
						filePath: qualificationListNew[qualificationListNew.length - 1].path,
						name: 'file', //与服务器端匹配
						success: (uploadFileRes) => {
							let data = JSON.parse(uploadFileRes.data);
							uni.hideLoading();
							if (data.code == 200) {
								attachfileids.push(data.data
									.id); // 返回服务器图片
								_self.qualificationList[_self.qualificationList.length - 1].upid = data
									.data.id
								// 图片全部上传后
								// if (attachfileids.length ==
								// 	qualificationListNew
								// 	.length) {
								// 整合新照片和旧照片的ID
								let ids = []
								if (_self.formData.qualification.length > 0) {
									ids = [...[_self.formData.qualification], ...
										attachfileids
									]
								} else {
									ids = [...attachfileids]
								}
								// let ids = [...(qualificationListOld
								// 		.map(e => e
								// 			.id)),
								// 	...
								// 	attachfileids
								// ]
								_self.formData.qualification = ids
									.join(
										","); //附件编号		
								resolve(attachfileids);
								// }
							} else {
								uni.showModal({
									content: '上传失败',
									showCancel: false
								})
							}
						},
						fail(e) {
							reject(e)
						}
					});
					// }
				} else {
					// 没有新照片时，需赋值最新的旧照片数据（可能进行了删除操作）
					let ids = [...(qualificationListOld.map(e => e.id))]
					_self.formData.qualification = ids.join(","); //附件编号		
					resolve(true)
				}
				// })
			},
			//验证vin码
			isCorrectVin(val) {
				return IsCorrectVin(val);
			},
			//修改车辆信息
			doModifyCarInfo() {
				let _self = this;
				request({
					url: Platform.api_requestUrl + '/stp-car/SaveOrUpdate',
					data: _self.formData,
					method: 'POST',
				}).then(response => {
					uni.hideLoading();
					if (response.code == 200) {
						uni.redirectTo({
							url: '/pages/car/my-car-list'
						})
					} else {
						_self.messageToggle('error', response.message || '提交失败');
					}
				}).catch(error => {
					uni.showModal({
						content: '修改车辆信息失败',
						showCancel: false
					})
				});
			},
		},
		watch: {
			'formData.drivingpermit'(val) {
				// 如果有17位，则开始请求后台，带出数据
				if (val.length == 17) {
					// do something
					this.formData.drivingpermit = val
				}

			}
		},
	}
</script>

<style lang="scss" scoped>
	.example {
		padding: 0 15px 15px 15px;
		background-color: #fff;
	}

	/deep/ .example .uni-forms-item__content {
		overflow: auto;
	}

	/deep/ .example .uni-section-header {
		padding: 5px 10px;
	}

	/deep/ .example .uni-input-input {
		text-align: right;
	}

	/deep/ .example .uni-input-placeholder {
		text-align: right;
	}

	/deep/ .example .uni-input-placeholder {
		text-align: right;
	}

	/deep/ .example .uni-easyinput__content {
		border-color: #fff !important;
	}

	/deep/ .example .uni-easyinput__content-input {
		text-align: right;
	}

	/deep/ .example .uni-forms-item__inner {
		border-bottom: 1px solid #e9e9e9;
		padding-bottom: 10px;
		padding-top: 15px;
		width: 100%;
		overflow: hidden;
	}

	/deep/ .example .uni-input {
		text-align: right;
		padding: 0;
	}

	/deep/ .example .uni-date-x {
		padding: 0;
	}

	/deep/ .example .uni-date__x-input {
		padding: 0;
		text-align: right;
	}

	/deep/ .example .uni-date-x--border {
		border: 0;
	}

	.btn-box {
		background: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: space-around;
		margin: 15px 10px;

		.btn1 {
			width: 90%;
			-webkit-flex: 1;
			background-color: $app-platform-color;
		}

		.btn2 {
			width: 90%;
			-webkit-flex: 1;
			color: $app-platform-color !important;
			border: 1px solid $app-platform-color !important;
		}
	}

	.platecode {
		font-size: 14px;
		margin-top: 8px;
		float: right;
		text-align: right;
		z-index: 999 !important;
	}

	.cartype {
		font-size: 14px;
		float: right;
		text-align: right;
	}

	.col-gap {
		width: 100vw;
		height: 12px;
		margin-left: -15px;
		margin-top: -1px;
		background-color: #e9e9e9;
	}

	/* 图片 */
	.add-box {
		padding: 15rpx 0;
		flex-wrap: wrap;
	}

	.add-img-box {
		display: flex;
		width: 100%;
		padding: 0 40rpx;
		padding-left: 10rpx;
		flex-direction: row;
		flex-wrap: wrap;
	}

	.add-img-item {
		/* width:210rpx;
		height:210rpx; */
		width: 150rpx;
		height: 150rpx;
		border-radius: 16rpx;
		position: relative;
		/* padding: 9rpx 0; */
		margin: 5rpx 10rpx;
	}

	.add-img-camera {
		flex: 1;
	}

	.add-img {
		width: 150rpx;
		height: 150rpx;
		border-radius: 16rpx;
	}

	.add-img-del {
		position: absolute;
		width: 40rpx;
		height: 40rpx;
		right: 8rpx;
		top: 17rpx;
		border-radius: 20rpx;
	}

	.color {
		line-height: 36px !important;
	}

	.vinbox {
		height: 100%;
		text-align: right;
		text-overflow: ellipsis;
		white-space: nowrap;
		overflow: hidden;
		padding: 8px 2px;
	}
</style>